package com.qf.lock;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class Lock {

    private static final String ZKADDR = "10.9.12.200:8601,10.9.12.200:8602,10.9.12.200:8603";
    private static CountDownLatch countDownLatch = new CountDownLatch(1);//用作阻塞的, 1 的意思是只需有一个地方执行了放行就放行所有阻塞的地方

    public static  int count=10;
    public static void  dijian()  {
        if(count>0){
            if(count==1){
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count--;
            System.out.println(count);
        }

    }
    public static void main(String[] args) throws IOException {


        for (int i=0;i<10;i++){
//            都创建Zookeeper 连接
            new Thread(){
                @Override
                public void run() {
                    CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                            .connectString(ZKADDR)
                            .connectionTimeoutMs(5000)
                            .retryPolicy(new ExponentialBackoffRetry(1000, 5))
                            .build();
                    curatorFramework.start();
//                  创建锁对象
                    InterProcessMutex interProcessMutex = new InterProcessMutex(curatorFramework, "/suolujing");

                    try {

                        countDownLatch.await();
                        System.out.println("请开始表演");
//                        抢锁  抢到的才会执行
                        interProcessMutex.acquire();
                        dijian();
                        interProcessMutex.release();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }.start();
        }
        countDownLatch.countDown();

        System.in.read();
    }

}
